package web.blogsphere.interceptor;

import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import web.blogsphere.constant.Constants;
import web.blogsphere.utils.JwtUtils;

/**
 * @ClassName LogInterceptor
 * @Description  登录的拦截器
 * @Author ZJX
 * @Date 2024/9/4 18:11
 * @Version 1.0
 */
@Component
@Slf4j
public class LogInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        1. 从header中获取token
        String token = request.getHeader(Constants.REQUEST_HEADER_TOKEN);
//        2. 校验 token 看是否拦截
        log.info("从header中获取token:{}", token);
        Claims claims = JwtUtils.parseToken(token);
        if (claims == null){
            response.setStatus(401); // 未登录
            return false;
        }
        return true;
    }
}
